var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
const app = getApp()
import {
  decryptData,
  encryptionData
} from '../../utils/public.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    residue: 1,
    hospInfo: {},
    userInfo: {},
    selecteId: 0,
    treatmentName: null,
    disabled: true,
    showDialog: false,
    options: [],
    addFrom: {},
    //蓝牙参数
    BTLTEST: '',
    btnFis: false,
    type: 1,
    deviceId: '',
    UUID1: '', //服务
    UUID2: '', //特征
    serviceId: '',
    characteristicId: '',
    commandEnd: '', //最终指令
    commandStart: '25', //最初指令
    deviceNo: '', //设备编号
    restrict: '', //是否为限制设备
    isLock: null,
    modelid: wx.getStorageSync('modelid'),
    restrictData: '', //数据包
    set001: '',
    set002: '',
    set003: '',
    setdata001: '',
    setdata002: '',
    setdata003: '',
    orderinfo: {},
    istrim: false
  },
  getList() {
    let that = this
    wx.request({
      url: app.globalData.serverUrlgdb + '/applet/treat/list',
      method: 'GET',
      header: {
        'token': wx.getStorageSync('token')
      },
      success: res => {
        let resData = res.data
        if (resData.code == 200) {
          resData.data.treatLists.map(item => {
            item.selected = false
          })
          that.setData({
            options: resData.data.treatLists
          })
          console.log(resData.data);
        }
      }
    })

  },
  bindtapItem(e) {
    let index = e.currentTarget.dataset.index
    let selecteId = this.data.selecteId
    let treatmentName = this.data.treatmentName
    let options = this.data.options
    options.map((v, i) => {
      if (v.treatmentId == index) {
        v.selected = !v.selected
        if (v.selected) {
          selecteId = v.treatmentId
          treatmentName = v.treatmentName
        } else {
          selecteId = 0
        }
      } else {
        v.selected = false
      }
    })
    this.setData({
      options,
      selecteId,
      treatmentName,
      disabled: selecteId == 0 ? true : false,
      'addFrom.treatmentId': selecteId,
      'addFrom.treatmentName': treatmentName,
    })
  },
  colsFun() {
    let that = this
    wx.scanCode({
      // onlyFromCamera: true,
      success(resCode) {
        if (resCode.errMsg == "scanCode:ok") {
          console.log(resCode, '扫码内容');
          if (!resCode.result.match(RegExp(/JJG/))) {
            that.showDialog({
              title: '无效二维码',
              icon: 'fail',
              tip: ['请扫描设备背部二维码']
            })
            return
          }
          let deviceNo = ''
          if (!resCode.result.match(RegExp(/TL/))) {
            that.setData({
              restrict: ''
            })
            deviceNo = resCode.result.split(';')[2]
          } else {
            that.setData({
              restrict: 'TL'
            })
            deviceNo = resCode.result.split(';')[3]
          }
          wx.request({
            url: app.globalData.serverUrlgdb + '/device/check/' + deviceNo,
            method: 'GET',
            header: {
              'token': wx.getStorageSync('token')
            },
            success: resdeviceNo => {
              if (resdeviceNo.data.code != 200) {
                that.setData({
                  selecteId: 0,
                  disabled: true
                })
              }
              if (resdeviceNo.data.code == 200) {
                let indexFirst = resCode.result.indexOf(';')
                let newYCL = resCode.result.slice(0, indexFirst)
                wx.setStorageSync('chb_key', that.addObjret(newYCL));
                that.setData({
                  btnFis: false,
                  BTLTEST: that.addObjret(newYCL),
                  deviceNo: deviceNo,
                  'addFrom.deviceNo': deviceNo,
                })
                if (that.data.modelid == 'iPhone') {
                  that.startBluetoothDeviceDiscovery()
                } else {
                  wx.openBluetoothAdapter({
                    success: (res) => {
                      console.log(res);
                      //已打开
                      wx.getBluetoothAdapterState({
                        //蓝牙的匹配状态
                        success: (res1) => {
                          console.log(res1, "本机设备的蓝牙已打开");
                          //生成密钥存储
                          let keys;
                          keys = wx.getStorageSync('chb_key').split(':')
                          wx.setStorageSync('key_K', that.keysfun(keys))
                          that.setData({
                            deviceId: wx.getStorageSync('chb_key')
                          })
                          wx.setStorageSync('deviceId', wx.getStorageSync('chb_key'))
                          that.createBLEConnection(wx.getStorageSync('chb_key'))
                        },
                        fail(error) {
                          if (wx.getStorageSync('brand') == 'HUAWEI') {
                            that.showDialogt({
                              title: '附近设备为允许',
                              icon: 'fail',
                              tip: ['请前往设置-应用权限', '微信允许附近设备']
                            })
                          } else {
                            that.showDialogt({
                              title: '手机蓝牙未打开',
                              icon: 'fail',
                              tip: ['请前往设置-应用内打开', '手机蓝牙']
                            })
                          }
                          wx.hideLoading()
                          that.setData({
                            btnFis: false
                          })
                        },
                      });
                    },
                    fail: (err) => {
                      console.log(err);
                      that.showDialogt({
                        title: '手机蓝牙未打开',
                        icon: 'fail',
                        tip: ['请前往设置-应用内打开', '手机蓝牙']
                      })
                      wx.hideLoading()
                      that.setData({
                        btnFis: false
                      })
                    }
                  })

                }
              } else if (resdeviceNo.data.code == 5016) {
                that.showDialogt({
                  title: '该设备已出租',
                  icon: 'fail',
                  tip: ['请将设备归还后在进行配置']
                })
                wx.closeBluetoothAdapter()
                wx.hideLoading()
              } else if (resdeviceNo.data.code == 5012) {
                that.showDialogt({
                  title: '该设备已损坏',
                  icon: 'fail',
                  tip: ['请联系厂家维修设备']
                })
                wx.closeBluetoothAdapter()
                wx.hideLoading()
              } else if (resdeviceNo.data.code == 5015) {
                that.showDialogt({
                  title: '非本科室设备',
                  icon: 'fail',
                  tip: ['非本科室设备无法', '进行任何操作']
                })
                wx.closeBluetoothAdapter()
                wx.hideLoading()
              } else if (resdeviceNo.data.code == 5013) {
                that.showDialogt({
                  title: resdeviceNo.data.message,
                  icon: 'fail',
                  tip: ['']
                })
                wx.closeBluetoothAdapter()
                wx.hideLoading()
              } else {
                if (resdeviceNo.data.message.indexOf(',')) {
                  let arr = resdeviceNo.data.message.split(',')
                  let arr1 = []
                  arr.map((item, index) => {
                    if (index != 0) {
                      arr1.push(item)
                    }
                  })
                  that.showDialogt({
                    title: arr[0],
                    icon: 'fail',
                    tip: [arr1]
                  })
                  wx.closeBluetoothAdapter()
                  wx.hideLoading()
                } else {
                  that.showDialogt({
                    title: resdeviceNo.data.message,
                    icon: 'fail',
                    tip: ['']
                  })
                  wx.closeBluetoothAdapter()
                  wx.hideLoading()
                }
              }
            }
          })




        }
      },
      fail() {
        that.setData({
          selecteId: 0,
          disabled: true
        })
        wx.hideLoading()
      }
    })
  },
  showDialog({
    title,
    tip,
    icon
  } = {}) {
    wx.hideLoading()
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialog').show()
  },
  showDialogt({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialogt').show()
  },
  shouquan() {
    wx.openSetting()
  },
  showDialogsq({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialogsq').show()
  },
  showDialogyes({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialogyes').show()
  },
  nodialogyes() {
    this.selectComponent('#dialogyes').hide()
  },
  hideDialog() {
    this.setData({
      showDialog: false
    })
  },
  getListinfo() {
    const that = this
    if (app.globalData.userInfo == '') {
      app.getUserInfo().then(res => {
        that.setData({
          userInfo: res
        })
      })
    } else {
      that.setData({
        userInfo: app.globalData.userInfo
      })
    }
    app.getHost(that.data.userInfo.hospitalId).then(res => {
      that.setData({
        hospInfo: res,
        custom: res.settlementUnit == 2 ? false : true,
        commandStart: res.rechargeTime
      })
    })
  },
  getrestrict() {
    let that = this
    let arr = []
    let isno = false
    if (that.data.set001 != '') {
      if (that.data.setdata001 == '') {
        isno = true
      }
      arr.push(that.restrictHeld(that.data.setdata001))
    }
    if (that.data.set002 != '') {
      if (that.data.setdata002 == '') {
        isno = true
      }
      arr.push(that.restrictHeld(that.data.setdata002))
    }
    if (that.data.set003 != '') {
      if (that.data.setdata003 == '') {
        isno = true
      }
      arr.push(that.restrictHeld(that.data.setdata003))
    }
    if (isno) {
      wx.hideLoading()
      wx.offBLEConnectionStateChange()
      if (wx.getStorageSync('deviceId')) {
        wx.closeBLEConnection({
          deviceId: wx.getStorageSync('deviceId'),
          success(res) {},
          fail(res) {}
        })
      }
      isno = false
      that.showDialogt({
        title: '查询失败，请重新操作!',
        icon: 'fail',
        tip: ['']
      })
      return
    }
    that.gettypeinfo(that.placeAnOrder(arr)).then(res => {
      console.log(res, '查询结果');
      wx.hideLoading()
      if (res.data.code == 200) {
        that.setData({
          orderinfo: that.placeAnOrder(arr)
        })
        that.orderHeld()
      } else if (res.data.code == 400322) {
        that.showDialogt({
          title: '治疗头与机构不符!',
          icon: 'fail',
          tip: ['']
        })
      } else if (res.data.code == 400323) {
        that.showDialogt({
          title: '治疗头全部报废,请更换!',
          icon: 'fail',
          tip: ['']
        })
      } else if (res.data.code == 400321) {
        that.setData({
          orderinfo: that.placeAnOrder(arr)
        })
        that.showDialogyes({
          title: '治疗头存在报废,是否继续?',
          icon: 'warning',
          tip: ['']
        })

      }
    })
    // that.placeAnOrder(arr)
    // that.BleWrite(encryptionData(arra, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
  },
  orderHeld() {
    let that = this
    let strs = that.data.userInfo.hospital.thLifeSpan
    let arra = 'AA44' + that.compensationsls(strs) + '24' + that.hexXorSum('AA44' + that.compensationsls(strs) + '24') + 'FFFFFFFFFFFFFFFF'
    console.log(that.compensations(strs), arra, 'shijian');
    that.BleWrite(encryptionData(arra, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
  },
  orderYesEnd() {
    let that = this
    that.placeRecharge(that.data.orderinfo).then(res => {
      if (res.data.code == 200) {
        wx.offBLEConnectionStateChange()
        wx.hideLoading({
          success: (res) => {
            that.showDialogt({
              title: '传输成功',
              icon: 'success',
              tip: ['可以使用设备进行治疗了！']
            })
            wx.removeStorageSync('deviceId')
            wx.removeStorageSync('UUID1')
            wx.removeStorageSync('UUID2')
            wx.removeStorageSync('key_K')
            wx.removeStorageSync('chb_key')
            if (wx.getStorageSync('deviceId')) {
              wx.closeBLEConnection({
                deviceId: wx.getStorageSync('deviceId'),
                success(res) {},
                fail(res) {}
              })
            }
            wx.closeBluetoothAdapter({
              success(res) {},
              fail(res) {}
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 1500)
          },
        })
      }
    })
  },
  placeRecharge(data) {
    let that = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.serverUrlgdb + '/dic/order/lifeSpan',
        method: 'POST',
        header: {
          'token': wx.getStorageSync('token')
        },
        data: data,
        success: res => {
          resolve(res)
        }
      })
    })
  },
  placeAnOrder(data) {
    let that = this
    let addFrom = {}
    addFrom.lifeSpanList = data
    addFrom.treatmentId = that.data.addFrom.treatmentId
    addFrom.treatmentName = that.data.addFrom.treatmentName
    addFrom.dicAddress = that.data.addFrom.dicAddress
    addFrom.deviceNo = that.data.addFrom.deviceNo
    return addFrom
  },
  //查询治疗头是否存在
  gettypeinfo(data) {
    let that = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.serverUrlgdb + '/dic/lifeSpan/check',
        method: 'POST',
        header: {
          'token': wx.getStorageSync('token')
        },
        data: data,
        success: res => {
          resolve(res)
        }
      })
    })

  },
  //数据处理函数
  restrictHeld(data) {
    let dataform = {}
    let strgdt = data.substr(6, 2)
    let str001 = data.substr(8, 2)
    let str002 = data.substr(10, 2)
    let str003 = data.substr(12, 8)
    let isScrapped = data.substr(20, 2) == '01' ? 1 : 0
    dataform.isScrapped = isScrapped
    // dataform.isScrapped = 0
    let aisle = ''
    let model = ''
    if (strgdt == '00') {
      dataform.spanNo = this.data.set003
    } else if (strgdt == '02') {
      dataform.spanNo = this.data.set002
    } else {
      dataform.spanNo = this.data.set001
    }
    if (str001 == '01') {
      aisle = '一'
    } else if (str001 == '02') {
      aisle = '二'
    } else {
      aisle = '三'
    }
    if (str002 == '01') {
      model = 'A4'
    } else if (str002 == '02') {
      model = 'A5'
    } else {
      model = 'A3'
    }
    dataform.type = model
    dataform.channel = aisle
    dataform.usedDuration = parseInt(str003, 16)
    console.log(dataform, parseInt(str003, 16));
    return dataform
  },
  // 蓝牙
  bindtapNext() {
    let that = this
    let lock = null
    let locationEnabled = false
    let locationAuthorized = false
    let bluetoothEnabled = false
    if (!that.data.isLock) {
      that.setData({
        isLock: new Date().getTime()
      })
    } else {
      lock = new Date().getTime()
    }
    if (that.data.isLock && lock) {
      if (lock - that.data.isLock < app.globalData.isNumLock) {
        return
      } else {
        that.setData({
          isLock: lock
        })
      }
    }
    if (that.data.hospInfo.availableNum < 1 && that.data.hospInfo.controlType == 0) {
      that.setData({
        showDialog: true
      })
    } else {
      wx.getSystemInfo({
        success(resd) {
          console.log(resd, '设备');
          locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
          locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
          bluetoothEnabled = resd.bluetoothEnabled; //判断蓝牙服务是否开启
          if (!locationEnabled) {
            that.showDialogt({
              title: '手机未打开定位功能',
              icon: 'fail',
              tip: ['']
            })
            wx.closeBluetoothAdapter()
            that.setData({
              btnFis: false
            })
          } else if (!locationAuthorized) {
            that.showDialogt({
              title: '微信未授权定位权限',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '微信定位信息权限']
            })
            wx.closeBluetoothAdapter()
            that.setData({
              btnFis: false
            })
          } else if (!bluetoothEnabled) {
            that.showDialogt({
              title: '手机蓝牙未打开',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '手机蓝牙']
            })
            wx.hideLoading()
            wx.closeBluetoothAdapter()
            that.setData({
              btnFis: false
            })
          } else {
            wx.getSetting({
              success: res => {
                console.log(res);
                let authSetting = res.authSetting
                if (authSetting['scope.userLocation']) {
                  if (authSetting['scope.bluetooth'] == undefined) {
                    wx.authorize({
                      scope: 'scope.bluetooth',
                      success(resp) {
                        if (resp.errMsg == "authorize:ok") {
                          wx.getLocation({
                            type: 'wgs84',
                            success(res) {
                              const latitude = res.latitude
                              const longitude = res.longitude
                              qqmapsdk.reverseGeocoder({
                                location: {
                                  latitude: latitude,
                                  longitude: longitude
                                },
                                success: (res => {
                                  let resultDataIt = res.result.formatted_addresses
                                  wx.setStorageSync('standardAddress', resultDataIt.standard_address)
                                  that.setData({
                                    'addFrom.dicAddress': resultDataIt.standard_address,
                                  })
                                  that.colsFun()
                                })
                              })
                            }
                          })
                        }
                      }
                    })
                  } else {
                    if (authSetting['scope.bluetooth']) {
                      wx.showLoading({
                        title: '下单中...',
                        icon: 'none',
                        mask: true
                      })
                      wx.getLocation({
                        type: 'wgs84',
                        success(res) {
                          const latitude = res.latitude
                          const longitude = res.longitude
                          qqmapsdk.reverseGeocoder({
                            location: {
                              latitude: latitude,
                              longitude: longitude
                            },
                            success: (res => {
                              let resultDataIt = res.result.formatted_addresses
                              wx.setStorageSync('standardAddress', resultDataIt.standard_address)
                              that.setData({
                                'addFrom.dicAddress': resultDataIt.standard_address,
                              })
                              that.colsFun()
                            })
                          })
                        }
                      })
                    } else {
                      that.showDialogsq({
                        title: '请给予蓝牙权限',
                        icon: 'warning',
                        tip: ['']
                      })
                      that.setData({
                        selecteId: 0,
                        disabled: true
                      })
                      wx.hideLoading()
                    }
                  }
                } else {
                  that.showDialogsq({
                    title: '请给予微信定位权限',
                    icon: 'warning',
                    tip: ['']
                  })
                  that.setData({
                    selecteId: 0,
                    disabled: true
                  })
                  wx.hideLoading()
                }
              }
            })
          }
        },
        fail() {
          that.showDialogt({
            title: '手机未打开定位功能',
            icon: 'fail',
            tip: ['']
          })
          wx.hideLoading()
        }
      })
    }

  },
  createBLEConnection(deviceId) {
    let that = this
    wx.showLoading({
      title: '设备搜索中',
      mask: true
    })
    let trimA = setTimeout(() => {
      if (wx.getStorageSync('timeiS')) {
        if (wx.getStorageSync('timeiS') >= 2) {
          that.showDialogt({
            title: '蓝牙未响应',
            icon: 'fail',
            tip: ['请前往设置-应用内打开手机蓝牙', '请勿下拉打开蓝牙！']
          })
          that.setData({
            btnFis: false
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 2000)
        } else {
          wx.setStorageSync('timeiS', Number(wx.getStorageSync('timeiS')) + 1)
          that.showDialogt({
            title: '蓝牙未响应',
            icon: 'fail',
            tip: ['请重新打开设备蓝牙', '并重新扫描二维码。']
          })
          that.setData({
            btnFis: false
          })
        }
      } else {
        wx.setStorageSync('timeiS', 1)
        that.showDialogt({
          title: '蓝牙未响应',
          icon: 'fail',
          tip: ['请重新打开设备蓝牙', '并重新扫描二维码。']
        })
      }
      wx.closeBLEConnection()
      wx.closeBluetoothAdapter()
      clearTimeout(trimA)
      trimA = null
      wx.hideLoading()
    }, 5000)
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success(rest) {
        wx.hideLoading()
        wx.removeStorageSync('timeiS')
        clearTimeout(trimA)
        trimA = null
        setTimeout(() => {
          that.getBLEDeviceServices(deviceId);
        }, 1000)
        wx.stopBluetoothDevicesDiscovery({
          success(res) {}
        });
      },
      fail(err) {
        wx.closeBLEConnection()
        wx.closeBluetoothAdapter()
        // if(trimA){
        //   that.showDialog({
        //     title: '蓝牙访问失败',
        //     icon: 'fail',
        //     tip: ['请重新扫码']
        //   })
        // }
        // clearTimeout(trimA)
        // trimA = null
        // wx.hideLoading()
        that.setData({
          btnFis: false
        })

      }
    });
  },
  //设备指令 蓝牙数据
  startBluetoothDeviceDiscovery() {
    let that = this;
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log(res);
        //已打开
        wx.getBluetoothAdapterState({
          //蓝牙的匹配状态
          success: (res1) => {
            console.log(res1, "本机设备的蓝牙已打开");
            //生成密钥存储
            console.log('开始搜索蓝牙设备')
            wx.startBluetoothDevicesDiscovery({
              success: (res) => {
                console.log(res, '搜索到的设备');
                // // 发现外围设备
                wx.showLoading({
                  title: '设备搜索中',
                  mask: true
                })
                that.getDeviceId().then(response => {
                  console.log(response, '查看返回值');
                  if (response == undefined) {
                    that.showDialogt({
                      title: '设备蓝牙未打开',
                      icon: 'fail',
                      tip: ['请检查设备蓝牙是否打开；', '设备电量是否充足。']
                    })
                    wx.closeBluetoothAdapter()
                    return
                  }
                  //生成密钥存储
                  let keys;
                  keys = response.newdeviceId.split(':')
                  wx.setStorageSync('key_K', that.keysfun(keys))
                  that.setData({
                    deviceId: response.deviceId,
                    btnFis: false
                  })
                  try {
                    wx.setStorageSync('deviceId', that.data.deviceId)
                  } catch (e) {
                    //TODO handle the exception
                  }
                  let deviceId = response.deviceId;
                  if (deviceId) {
                    wx.createBLEConnection({
                      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                      deviceId,
                      success(rest) {
                        wx.hideLoading()
                        setTimeout(() => {
                          that.getBLEDeviceServices(deviceId);
                        }, 1000)
                        wx.stopBluetoothDevicesDiscovery({
                          success(res) {}
                        });
                      },
                      fail(err) {
                        console.log(err);
                      }
                    });
                  }
                })
              }
            })
          },
          fail(error) {
            if (wx.getStorageSync('brand') == 'HUAWEI') {
              that.showDialogt({
                title: '附近设备为允许',
                icon: 'fail',
                tip: ['请前往设置-应用权限', '微信允许附近设备']
              })
            } else {
              that.showDialogt({
                title: '手机蓝牙未打开',
                icon: 'fail',
                tip: ['请前往设置-应用内打开', '手机蓝牙']
              })
            }
            wx.hideLoading()
            that.setData({
              btnFis: false
            })
          },
        });
      },
      fail: (err) => {
        console.log(err);
        that.showDialogt({
          title: '手机蓝牙未打开',
          icon: 'fail',
          tip: ['请前往设置-应用内打开', '手机蓝牙']
        })
        wx.hideLoading()
        that.setData({
          btnFis: false
        })
      }
    })
  },

  getBLEDeviceServices(deviceId) {
    let that = this;
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      success: (res) => {
        console.log(res, '连接成功返回值');
        wx.onBLEConnectionStateChange(function (res) {
          // 该方法回调中可以用于处理连接意外断开等异常情况
          if (!res.connected) {
            that.showDialog({
              title: '蓝牙已断开',
              icon: 'fail',
              tip: ['请重新扫码连接']
            })
            wx.offBLEConnectionStateChange()
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 2000)
          }
        })
        if (res.services) {
          let resA = res.services
          res.services.map((item, index) => {
            if (item.isPrimary) {
              wx.getBLEDeviceCharacteristics({
                deviceId,
                serviceId: item.uuid,
                success: (resServe) => {
                  console.log(resServe, '蓝牙服务');
                  resServe.characteristics.map(vtm => {
                    if (vtm.uuid == '0000FFF6-0000-1000-8000-00805F9B34FB') {
                      that.setData({
                        UUID1: resA[index].uuid,
                        UUID2: vtm.uuid
                      })
                      try {
                        wx.setStorageSync('UUID1',
                          that.data.UUID1)
                        wx.setStorageSync('UUID2',
                          that.data.UUID2)
                        if (that.data.restrict == '') {
                          wx.showLoading({
                            title: '正在充值...',
                            mask: true
                          })
                          let arra = 'AA42' + that.compensation(that.data.commandStart) + '24' + that.hexXorSum('AA42' + that.compensation(that.data.commandStart) + '24') + 'FFFFFFFFFFFFFFFFFFFF'
                          that.BleWrite(encryptionData(arra, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
                        } else {
                          wx.showLoading({
                            title: '正在查询...',
                            mask: true
                          })
                          let arra = 'AA43000024CDFFFFFFFFFFFFFFFFFFFF'
                          that.BleWrite(encryptionData(arra, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
                        }

                      } catch (e) {
                        //TODO handle the exception
                      }
                      that.notifyBLECharacteristicValueChange(
                        deviceId, that.data.UUID1,
                        that.data.UUID2, true);
                    }
                  })
                }
              })
              console.log(item.uuid, '设备UUID');
            }
          })

        }
      }
    })
  },
  // 向蓝牙写入数据
  BleWrite(instruction, characteristicIdA, serviceIdA) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let _this = this
    _this.setData({
      type: 1,
      istrim: true
    })
    // let serviceId = _this.serviceId
    let serviceId = serviceIdA;
    let characteristicId = characteristicIdA;
    let deviceId = _this.data.deviceId
    // const buffer = _this.hexStringToArrayBuffer(instruction);
    // const buffer = _this.hexStringToArrayBuffer1(instruction);
    const buffer = _this.hex2ArrayBuffer(instruction);
    // console.log('buffer=======================', buffer)
    wx.writeBLECharacteristicValue({
      deviceId, // 蓝牙设备 deviceId
      serviceId, // 蓝牙服务uuid,即第二个uuid
      characteristicId, // 蓝牙特征值的 (即 writeId)
      value: buffer, // 这里的value是ArrayBuffer类型
      success(res) {
        console.log('指令下发成功==', res.errMsg, res)
        console.log('指令下发成功传入的参数--characteristicId', characteristicId, '--serviceId：',
          serviceId)
        // wx.readBLECharacteristicValue({
        //   // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
        //   deviceId: deviceId,
        //   // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取  
        //   serviceId: serviceId,
        //   // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取  
        //   characteristicId: characteristicId,
        //   success: (res) => {
        //     console.log('readBLECharacteristicValue:success', res)
        //   },
        //   fail: (res) => {
        //     console.log('readBLECharacteristicValue:fail', res)
        //   }
        // })
      },
      fail(err) {
        console.log('写入数据失败', err)
        console.log('指令下发失败传入的参数--characteristicId', characteristicId, '--serviceId：',
          serviceId)
        wx.showToast({
          icon: "none",
          title: "请确保您的手机已连接设备",
          duration: 3000
        })
      }
    })
  },
  //监听开始和取消
  notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId, state) {
    let that = this;
    wx.notifyBLECharacteristicValueChange({
      state: state, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId,
      success(res) {
        console.log(res, '监听的值看看');
        let count = 0;
        let maxCount = 10;
        let trem = setInterval(() => {
          count++
          if (count == maxCount) {
            clearInterval(trem)
            if (that.data.istrim) {
              wx.hideLoading()
              wx.offBLEConnectionStateChange()
              if (wx.getStorageSync('deviceId')) {
                wx.closeBLEConnection({
                  deviceId: wx.getStorageSync('deviceId'),
                  success(res) {},
                  fail(res) {}
                })
              }
              that.setData({
                istrim: false
              })
              that.showDialogt({
                title: '已超时请重新操作!',
                icon: 'fail',
                tip: ['']
              })
            }
            console.log('结束');
          } else {
            console.log(count);
          }
        }, 1000)
        if (!state) {
          that.notifyBLECharacteristicValueChange(that.data.deviceId, that.data.serviceId, that.data
            .characteristicId, true);
        }
        wx.onBLECharacteristicValueChange(
          function (resa) {
            console.log(resa, '监听Value变化');
            clearInterval(trem)
            that.setData({
              istrim: false
            })
            if (that.data.type == 1) {
              let a = that.buf2hex(resa.value)
              let successAC = decryptData(a, wx.getStorageSync('key_K')).substr(0, 8)
              console.log(successAC, '成功截取', decryptData(a, wx.getStorageSync('key_K')));
              if (successAC == 'aa4200e8') {
                if (wx.getStorageSync('postis')) {
                  return
                }
                wx.setStorageSync('postis', successAC)
                if (that.data.restrict == 'TL') {
                  that.orderYesEnd()
                } else {
                  wx.request({
                    url: app.globalData.serverUrlgdb + '/dic/order',
                    method: 'POST',
                    header: {
                      'token': wx.getStorageSync('token')
                    },
                    data: that.data.addFrom,
                    success: res => {
                      if (res.data.code == 200) {
                        wx.offBLEConnectionStateChange()
                        wx.hideLoading({
                          success: (res) => {
                            that.showDialogt({
                              title: '传输成功',
                              icon: 'success',
                              tip: ['可以使用设备进行治疗了！']
                            })
                            wx.removeStorageSync('deviceId')
                            wx.removeStorageSync('UUID1')
                            wx.removeStorageSync('UUID2')
                            wx.removeStorageSync('key_K')
                            wx.removeStorageSync('chb_key')
                            if (wx.getStorageSync('deviceId')) {
                              wx.closeBLEConnection({
                                deviceId: wx.getStorageSync('deviceId'),
                                success(res) {},
                                fail(res) {}
                              })
                            }
                            wx.closeBluetoothAdapter({
                              success(res) {},
                              fail(res) {}
                            })
                            setTimeout(() => {
                              wx.navigateBack({
                                delta: 1,
                              })
                            }, 1500)
                          },
                        })
                      }
                    }
                  })
                }


              } else if (successAC == 'aa4201e9' || successAC == 'aa2201e9') {
                wx.hideLoading()
                wx.offBLEConnectionStateChange()
                if (wx.getStorageSync('deviceId')) {
                  wx.closeBLEConnection({
                    deviceId: wx.getStorageSync('deviceId'),
                    success(res) {},
                    fail(res) {}
                  })
                }
                that.showDialogt({
                  title: '充值失败',
                  icon: 'fail',
                  tip: ['请重新操作']
                })
              } else if (successAC == 'aa4301e8') {
                wx.hideLoading()
                wx.offBLEConnectionStateChange()
                if (wx.getStorageSync('deviceId')) {
                  wx.closeBLEConnection({
                    deviceId: wx.getStorageSync('deviceId'),
                    success(res) {},
                    fail(res) {}
                  })
                }
                that.showDialogt({
                  title: '设备未接入治疗头请接入治疗头在进行充值',
                  icon: 'fail',
                  tip: ['']
                })
              } else if (successAC == 'aa430000') {
                that.setData({
                  setdata003: decryptData(a, wx.getStorageSync('key_K'))
                })
                if (that.data.set001 != '' && that.data.setdata001 == '') {
                  wx.hideLoading()
                  wx.offBLEConnectionStateChange()
                  if (wx.getStorageSync('deviceId')) {
                    wx.closeBLEConnection({
                      deviceId: wx.getStorageSync('deviceId'),
                      success(res) {},
                      fail(res) {}
                    })
                  }
                  that.showDialogt({
                    title: '查询失败',
                    icon: 'fail',
                    tip: ['请重新操作']
                  })
                  return
                }
                if (that.data.set002 != '' && that.data.setdata002 == '') {
                  wx.hideLoading()
                  wx.offBLEConnectionStateChange()
                  if (wx.getStorageSync('deviceId')) {
                    wx.closeBLEConnection({
                      deviceId: wx.getStorageSync('deviceId'),
                      success(res) {},
                      fail(res) {}
                    })
                  }
                  that.showDialogt({
                    title: '查询失败',
                    icon: 'fail',
                    tip: ['请重新操作']
                  })
                  return
                }
                if (that.data.set003 != '' && that.data.setdata003 == '') {
                  wx.hideLoading()
                  wx.offBLEConnectionStateChange()
                  if (wx.getStorageSync('deviceId')) {
                    wx.closeBLEConnection({
                      deviceId: wx.getStorageSync('deviceId'),
                      success(res) {},
                      fail(res) {}
                    })
                  }
                  that.showDialogt({
                    title: '查询失败',
                    icon: 'fail',
                    tip: ['请重新操作']
                  })
                  return
                }
                if (that.data.setdata001 != '' && that.data.set001 == '') {
                  wx.hideLoading()
                  wx.offBLEConnectionStateChange()
                  if (wx.getStorageSync('deviceId')) {
                    wx.closeBLEConnection({
                      deviceId: wx.getStorageSync('deviceId'),
                      success(res) {},
                      fail(res) {}
                    })
                  }
                  that.showDialogt({
                    title: '查询失败',
                    icon: 'fail',
                    tip: ['请重新操作']
                  })
                  return
                }
                if (that.data.setdata002 != '' && that.data.set002 == '') {
                  wx.hideLoading()
                  wx.offBLEConnectionStateChange()
                  if (wx.getStorageSync('deviceId')) {
                    wx.closeBLEConnection({
                      deviceId: wx.getStorageSync('deviceId'),
                      success(res) {},
                      fail(res) {}
                    })
                  }
                  that.showDialogt({
                    title: '查询失败',
                    icon: 'fail',
                    tip: ['请重新操作']
                  })
                  return
                }
                if (that.data.setdata003 != '' && that.data.set003 == '') {
                  wx.hideLoading()
                  wx.offBLEConnectionStateChange()
                  if (wx.getStorageSync('deviceId')) {
                    wx.closeBLEConnection({
                      deviceId: wx.getStorageSync('deviceId'),
                      success(res) {},
                      fail(res) {}
                    })
                  }
                  that.showDialogt({
                    title: '查询失败',
                    icon: 'fail',
                    tip: ['请重新操作']
                  })
                  return
                }
                that.getrestrict()
              } else if (successAC == 'aa430001') {
                that.setData({
                  set003: decryptData(a, wx.getStorageSync('key_K')).substr(8, 20)
                })
              } else if (successAC == 'aa430002') {
                that.setData({
                  setdata002: decryptData(a, wx.getStorageSync('key_K'))
                })
              } else if (successAC == 'aa430003') {
                that.setData({
                  set002: decryptData(a, wx.getStorageSync('key_K')).substr(8, 20)
                })
              } else if (successAC == 'aa430004') {
                that.setData({
                  setdata001: decryptData(a, wx.getStorageSync('key_K'))
                })
              } else if (successAC == 'aa430005') {
                that.setData({
                  set001: decryptData(a, wx.getStorageSync('key_K')).substr(8, 20)
                })
              } else if (successAC == 'aa4400ee') {
                wx.showLoading({
                  title: '正在充值...',
                  mask: true
                })
                let arra = 'AA42' + that.compensation(that.data.commandStart) + '24' + that.hexXorSum('AA42' + that.compensation(that.data.commandStart) + '24') + 'FFFFFFFFFFFFFFFFFFFF'
                console.log(arra, '充值');
                setTimeout(() => {
                  that.BleWrite(encryptionData(arra, wx.getStorageSync('key_K')), that.data.UUID2, that.data.UUID1)
                }, 500)
              } else if (successAC == 'aa4401ef') {
                wx.hideLoading()
                wx.offBLEConnectionStateChange()
                if (wx.getStorageSync('deviceId')) {
                  wx.closeBLEConnection({
                    deviceId: wx.getStorageSync('deviceId'),
                    success(res) {},
                    fail(res) {}
                  })
                }
                that.showDialogt({
                  title: '充值失败',
                  icon: 'fail',
                  tip: ['请重新操作']
                })
              }
            } else {
              wx.hideLoading()
              wx.offBLEConnectionStateChange()
              if (wx.getStorageSync('deviceId')) {
                wx.closeBLEConnection({
                  deviceId: wx.getStorageSync('deviceId'),
                  success(res) {},
                  fail(res) {}
                })
              }
              that.showDialogt({
                title: '充值失败',
                icon: 'fail',
                tip: ['请重新操作']
              })
            }

          }
        );
      },
      fail(err) {
        wx.hideLoading()
        wx.offBLEConnectionStateChange()
        if (wx.getStorageSync('deviceId')) {
          wx.closeBLEConnection({
            deviceId: wx.getStorageSync('deviceId'),
            success(res) {},
            fail(res) {}
          })
        }
        that.showDialogt({
          title: '充值失败',
          icon: 'fail',
          tip: ['请重新操作']
        })
        console.log('报错了1', err)
      }
    });
  },
  // 发现外围设备
  getDeviceId() {
    let that = this;
    console.log("执行到这--发现外围设备1")
    return new Promise(function (resolve, reject) {
      let deviceId;
      let timer = setTimeout(() => {
        if (!deviceId) {
          wx.hideLoading()
          console.log('清理蓝牙监听', res)
          that.showDialogt({
            title: '设备蓝牙未打开',
            icon: 'fail',
            tip: ['']
          })
          wx.closeBluetoothAdapter()
          resolve(undefined);
          clearTimeout(timer);
          timer = null
        }
      }, 5000);
      wx.onBluetoothDeviceFound(function (devices) {
        console.log('发现的设备2', devices, '-----------', that.data.BTLTEST)
        // if(wx.getStorageSync('modelid')!='当前设备是其他类型'){
        let newdeviceId = that.addObjretIphone(devices.devices[0].name.slice(devices.devices[0].name.indexOf(' ') + 1))
        let newdeviceId1 = that.addObjretIphone1(devices.devices[0].name.slice(devices.devices[0].name.indexOf(' ') + 1))
        console.log(newdeviceId, '-----------', that.data.BTLTEST);
        if (newdeviceId == that.data.BTLTEST || newdeviceId1 == that.data.BTLTEST) {
          deviceId = devices.devices[0].deviceId;
          let a;
          a = {
            deviceId: devices.devices[0].deviceId,
            newdeviceId: newdeviceId == that.data.BTLTEST ? newdeviceId : newdeviceId1
          }
          resolve(a);
          clearTimeout(timer);
          timer = null
        }
      });
    });
  },
  // 指令异或和
  hexXorSum(str) {
    let that = this
    let arr = that.addObjret(str).split(':')
    return that.xorCalculator(arr)
  },
  xorCalculator(arr) {
    let that = this
    if (arr.length == 1) {
      return arr[0]
    }
    const first = arr.shift()
    const result = that.hexXor(first, that.xorCalculator(arr))
    return result;
  },

  // 异或计算法
  hexXor(hex1, hex2) {
    var binary1 = parseInt(hex1, 16).toString(2);
    var binary2 = parseInt(hex2, 16).toString(2);
    var maxLength = Math.max(binary1.length, binary2.length);
    binary1 = ('0'.repeat(maxLength) + binary1).slice(-maxLength);
    binary2 = ('0'.repeat(maxLength) + binary2).slice(-maxLength);
    var result = '';
    for (var i = 0; i < maxLength; i++) {
      if (binary1[i] != binary2[i]) {
        result += '1';
      } else {
        result += '0';
      }
    }
    return parseInt(result, 2).toString(16).toUpperCase();
  },
  // 时间补差
  compensation(data) {
    let hex16 = Number(data).toString(16)
    if (hex16.length % 2 == 0) {
      if (hex16.length == 2) {
        // return hex16 + '00'
        return '00' + hex16
      }
      return hex16
      // return hex16.substring(2) + hex16.substring(0, 2)
    } else {
      if (hex16.length == 1) {
        hex16 = '000' + hex16
        return hex16
      } else {
        hex16 = '0' + hex16
        return hex16
      }
      // return hex16.substring(2) + hex16.substring(0, 2)
    }
  },

  //限制时间补差
  compensations(data) {
    let hex16 = Number(data).toString(16)
    if (hex16.length % 2 == 0) {
      if (hex16.length == 2) {
        // return hex16 + '00'
        return '000000' + hex16
      } else if (hex16.length == 4) {
        return '0000' + hex16
      } else if (hex16.length == 6) {
        return '00' + hex16
      }
      return hex16
      // return hex16.substring(2) + hex16.substring(0, 2)
    } else {
      if (hex16.length == 1) {
        hex16 = '0000000' + hex16
        return hex16
      } else if (hex16.length == 3) {
        hex16 = '00000' + hex16
        return hex16
      } else if (hex16.length == 5) {
        hex16 = '000' + hex16
        return hex16
      } else if (hex16.length == 7) {
        hex16 = '0' + hex16
        return hex16
      }
      // return hex16.substring(2) + hex16.substring(0, 2)
    }
  },
  compensationsls(data) {
    let hex16 = Number(data*60).toString(16)
    if (hex16.length % 2 == 0) {
      if (hex16.length == 2) {
        // return hex16 + '00'
        return '000000' + hex16
      } else if (hex16.length == 4) {
        return '0000' + hex16
      } else if (hex16.length == 6) {
        return '00' + hex16
      }
      return hex16
      // return hex16.substring(2) + hex16.substring(0, 2)
    } else {
      if (hex16.length == 1) {
        hex16 = '0000000' + hex16
        return hex16
      } else if (hex16.length == 3) {
        hex16 = '00000' + hex16
        return hex16
      } else if (hex16.length == 5) {
        hex16 = '000' + hex16
        return hex16
      } else if (hex16.length == 7) {
        hex16 = '0' + hex16
        return hex16
      }
      // return hex16.substring(2) + hex16.substring(0, 2)
    }
  },

  // 密钥生成
  keysfun(data) {
    let that = this
    let strs = '545a5a594a4c41534552'
    console.log(data);
    data.map((item, index) => {
      let F = this.hexXor(item, '0' + (index + 1))
      if (F.length != 2) {
        F = '0' + F
      }
      console.log(F);

      strs += F.toString(16)
    })
    console.log(strs.length);
    return strs
  },
  // 16进制字符串转ArrayBuffer
  hex2ArrayBuffer(hex_str) {
    // let hex_str = 'AA5504B10000B5'
    let typedArray = new Uint8Array(hex_str.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    }))
    let buffer = typedArray.buffer
    return buffer
  },
  // ArrayBuffer转16进度字符串
  buf2hex(arrayBuffer) {
    return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2))
      .join('');
  },
  //处理字符
  addObjretIphone(data) {
    let result = "";
    let newarr = []
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    newarr = result.split(':')
    return newarr.reverse().join(':')
  },
  addObjretIphone1(data) {
    let result = "";
    let newarr = []
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    newarr = result.split(':')
    return newarr.join(':')
  },
  addObjret(data) {
    let result = "";
    for (let i = 0; i < data.length; i++) {
      if (i % 2 == 0 && i != 0) {
        result += ':' + data[i];
      } else {
        result += data[i];
      }
    }
    return result
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    that.setData({
      hospitalId: options.hospitalId
    })
    qqmapsdk = new QQMapWX({
      key: app.globalData.key
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this
    that.getList()
    that.getListinfo()
    if (wx.getStorageSync('postis')) {
      wx.removeStorageSync('postis')
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})